package model

import (
	"blog-service/global"
	"blog-service/pkg/setting"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

type Model struct {
	ID         uint32 `gorm:"primary_key" json:"id"`
	CreatedBy  string `json:"created_by"`
	ModifiedBy string `json:"modified_by"`
	CreatedOn  uint32 `json:"created_on"`
	ModifiedOn uint32 `json:"modified_on"`
	DeletedOn  uint32 `json:"deleted_on"`
	IsDel      uint8  `json:"is_del"`
}

func NewDBEngine(cfg *setting.DBSettingsS) (*gorm.DB, error) {
	dsn := "%s:%s@tcp(%s)/%s?charset=%s&parseTime=%t&loc=Local"
	//db链接参数
	dsn = fmt.Sprintf(dsn,
		cfg.UserName,
		cfg.PassWord,
		cfg.Host,
		cfg.DB,
		cfg.Charset,
		cfg.ParseTime,
	)
	extraConf := &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   cfg.Prefix, //设置表前缀
			SingularTable: true,       //表名称不使用复数
		},
		PrepareStmt: true, //全局模式，所有 DB 操作都会创建并缓存预编译语句
	}
	if global.Settings.Server.RunMode == "debug" {
		extraConf.Logger = logger.Default.LogMode(logger.Info)
	}
	db, err := gorm.Open(mysql.Open(dsn), extraConf)
	if err != nil {
		return nil, err
	}
	sqlDb, err := db.DB()
	if err != nil {
		return nil, err
	}
	//设置打开数据库链接的最大数量
	sqlDb.SetMaxOpenConns(cfg.MaxOpenConns)
	//设置空闲连接池中链接的最大数量
	sqlDb.SetMaxIdleConns(cfg.MaxIdleConns)
	return db, nil
}

func addExtraSpaceIfExist(str string) string {
	if str != "" {
		return " " + str
	}
	return ""
}